﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using static org.apache.zookeeper.ZooDefs;

namespace Coldairarrow.Business.Interface
{
    public class ZB_InventoryInterfaceBusiness : ZBInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption ZB_Query;
        public ZB_InventoryInterfaceBusiness()
        {
            this.InterfaceName = "ZB库存";
            //索引字段
            this.MapFields = GetMapField("ZB_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            ZB_Query = this.interfaceOption.Where(x => x.OperateType == "ZB_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ZB_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, ZB_NoQueryEventArgs ZB_NoQueryEventArgs)
        {
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, ZB_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取配置参数
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var parameters = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='PL'");
                long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                string apiKey = parameters.Where(x => x.Name == "APIKEY").First().Value;
                string nonce = parameters.Where(x => x.Name == "nonce").First().Value;
                string apiSecret = parameters.Where(x => x.Name == "APISECRET").First().Value;
                string signature = GenerateSignature(apiSecret, timestamp, nonce);
                string token = GenerateToken(apiKey, timestamp, nonce, signature);
                //设置请求头
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", token);
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };

                //设置单次查询的页面数量
                queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "pageSize").First().SourceField.ToInt();
                queryEventArgs.Page.PageIndex = 1;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, ZB_QueryEventArgs queryEventArgs)
        {
            //json参数
            ZB_ReqDTO data = new ZB_ReqDTO();
            data.commonParam.pageParam.pageNum = queryEventArgs.Page.PageIndex;
            queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, ZB_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                ZB_BaseResponseDTO<ZB_Inventory> result = (ZB_BaseResponseDTO<ZB_Inventory>)JsonConvert.DeserializeObject<ZB_BaseResponseDTO<ZB_Inventory>>(queryEventArgs.ResultStr);
                if (result.success)
                {
                    queryEventArgs.Success = true;
                    if (!result.data.IsNullOrEmpty() && result.data.list.Count < queryEventArgs.Page.PageSize)
                    {
                        //查询完成
                        queryEventArgs.Page.PageIndex = 1;
                        queryEventArgs.Page.Complete = true;
                        if (result.data.list.Count > 0) queryEventArgs.Rows = result.data.list;
                    }
                    else
                    {
                        //查询下一页
                        queryEventArgs.Page.PageIndex += 1;
                        queryEventArgs.Rows = result.data;
                    }
                }
                else
                {
                    queryEventArgs.Success = false;
                    AddLog(SqlDb, result.message, InterfaceName, "erro", "");
                }

            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //获取源数据
                List<ZB_Inventory> sourceData = await this.QueryAsync<ZB_Inventory>(this.ZB_Query, SqlDb);
                //拼接生成ID
                sourceData.ForEach(r =>
                {
                    r.ID = r.openProduct_productSku + r.openWarehouse_warehouseCode;
                    r.openWarehouse_warehouseCode =r.openWarehouse.warehouseCode;
                    r.openProduct_productSku = r.openProduct.productSku;
                    r.openProduct_name = r.openProduct.name;
                });
                //将重复的id编号变成唯一的id
                sourceData.GroupBy(x => x.ID).ForEach(x =>
                {
                    if (x.Count() > 1)
                    {
                        int c = 0;
                        x.ForEach(r =>
                        {
                            c++;
                            r.ID = r.ID + c;
                        });

                    }

                });


                if (sourceData.Count > 0)
                {
                    //同步数据库
                    SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(MapFields);
                    sqlDBInterface.ExecuteInterface<ZB_Inventory>(sourceData, "SD_ZB_Inventory");
                }
                else
                {
                    throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                }



            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }


        // 生成 token: apiKey-timestamp-nonce-signature 的 Base64 编码
        public string GenerateToken(string apiKey, long timestamp, string nonce, string signature)
        {
            string content = $"{apiKey}-{timestamp}-{nonce}-{signature}";
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            return Convert.ToBase64String(bytes);
        }

        // 生成签名（使用 HMAC-SHA256）
        public string GenerateSignature(string apiSecret, long timestamp, string nonce)
        {
            try
            {
                // 构建待签名字符串：timestamp + "-" + nonce
                string dataToSign = $"{timestamp}-{nonce}";

                using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(apiSecret)))
                {
                    byte[] dataBytes = Encoding.UTF8.GetBytes(dataToSign);
                    byte[] signatureBytes = hmac.ComputeHash(dataBytes);
                    return Convert.ToBase64String(signatureBytes);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("API签名生成失败", ex);
            }
        }

    }

}
